package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"main/controller"
	"main/tool"
	"net/http"
)

func main() {
	cfg, err := tool.ParseConfig("./config/app.json")
	if err != nil {
		panic(err)
	}

	// 初始化DB实例
	if _, err := tool.NewOrmEngine(cfg); err != nil {
		log.Printf("connect db failed: %v", err)
		return
	}
	// 初始化redis
	tool.InitRedisStore()
	tool.InitCaptchaService()

	app := gin.Default()
	app.Use(Cors())
	tool.InitSession(app)

	registerRouter(app)

	if err := app.Run(fmt.Sprintf("%s:%d", cfg.AppHost, cfg.AppPort)); err != nil {
		panic(err)
	}
}

func registerRouter(router *gin.Engine) {
	new(controller.HelloController).Router(router)
	new(controller.MemberController).Router(router)
	new(controller.FoodCategoryController).Router(router)
	new(controller.ShopController).Router(router)
	new(controller.GoodController).Router(router)
}

func Cors() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		method := ctx.Request.Method

		ctx.Header("Access-Control-Allow-Origin", "*")
		ctx.Header("Access-Control-Allow-Methods", "*")
		ctx.Header("Access-Control-Allow-Headers", "*")

		if method == http.MethodOptions {
			// options 直接返回204
			ctx.AbortWithStatus(http.StatusNoContent)
		}
	}
}
